package cn.edu.zjicm.wordsnet_d.view;

import java.util.Calendar;

import android.app.DatePickerDialog;
import android.content.Context;
import android.widget.DatePicker;
import android.widget.Toast;

public class LimitedRangeDatePickerDialog extends DatePickerDialog {

	private Calendar minDate;
	private Calendar maxDate;
	private Context context;
	//private java.text.DateFormat mTitleDateFormat;

	public LimitedRangeDatePickerDialog(Context context,
			DatePickerDialog.OnDateSetListener callBack, int year,
			int monthOfYear, int dayOfMonth, Calendar minDate,
			Calendar maxDate) {
		super(context, callBack, year, monthOfYear, dayOfMonth);
		this.context = context;
		this.minDate = minDate;
		this.maxDate = maxDate;
		// mTitleDateFormat = java.text.DateFormat
		// .getDateInstance(java.text.DateFormat.FULL);
	}

	public void onDateChanged(DatePicker view, int year, int month, int day) {
		Calendar newDate = Calendar.getInstance();
		newDate.set(year, month, day);

		if (minDate != null && isDateBefore(newDate)) {
			view.init(minDate.get(Calendar.YEAR), minDate.get(Calendar.MONTH),
					minDate.get(Calendar.DAY_OF_MONTH), this);
			Toast.makeText(context, "每天单词学习数量不能超过600个", // "每天单词学习数量不能超过600个"
					Toast.LENGTH_SHORT).show();
			// setTitle(mTitleDateFormat.format(minDate.getTime()));
		} else if (maxDate != null && isDateAfter(newDate)) {
			view.init(maxDate.get(Calendar.YEAR), maxDate.get(Calendar.MONTH),
					maxDate.get(Calendar.DAY_OF_MONTH), this);
			Toast.makeText(context, "学习周期不能超过一年", Toast.LENGTH_SHORT).show();
			// setTitle(mTitleDateFormat.format(maxDate.getTime()));
		} else {
			view.init(year, month, day, this);
			// setTitle(mTitleDateFormat.format(newDate.getTime()));
		}
	}
	
	private boolean isDateBefore(Calendar planEndDate) {
		return planEndDate.getTimeInMillis() / 1000 / 60 / 60 / 24
				- minDate.getTimeInMillis() / 1000 / 60 / 60 / 24 < 0;
	}
    
	private boolean isDateAfter(Calendar planEndDate) {
		return planEndDate.getTimeInMillis() / 1000 / 60 / 60 / 24
				- maxDate.getTimeInMillis() / 1000 / 60 / 60 / 24 > 0;
	}
}
